package com.rabbitmq.origin.api;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.common.utils.RabbitMqUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author
 * @Describe headers类型交换机,
 * Headers Exchange不同于上面三种Exchange，它是根据Message的一些头部信息来分发过滤Message，忽略routing key的属性。
 * 如果Headers信息和message消息的头信息相匹配，那么这条消息就匹配上了。
 * @date
 */
@Slf4j(topic = "RabbitMqProviderHeaders")
public class RabbitMqProviderHeaders {

    /**
     * headers方式
     */
    public void publishHeaders(String exchangeName, Map<String, Object> headers, String msg) {
        Connection conn = null;
        Channel channel = null;
        try {
            // 获取连接
            conn = RabbitMqUtil.getConn();
            // 创建通道（通道可用于消息的发送和接收）
            channel = conn.createChannel();

            // 主题方式的交换机
            channel.exchangeDeclare(exchangeName, BuiltinExchangeType.HEADERS, true);

            // 构建headers
            AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
            builder.headers(headers);

            // 发布消息,消息发送到消费端绑定的队列参数的内容为发送时设置的属性内容子集的消费者进行消费
            channel.basicPublish(exchangeName, "", builder.build(), msg.getBytes());
        } catch (Exception e) {
            log.error("发布消息异常,", e);
        } finally {
            // log.info("[RabbitMqProviderHeaders] publishHeaders 关闭资源连接");
            RabbitMqUtil.close(conn, channel);
        }
    }
}
